/*
 * @Date: 2022-03-29 12:52:42
 * @LastEditors: LiuPeng
 * @LastEditTime: 2022-04-11 18:18:13
 * @FilePath: \pay\src\pages\AgencyPay\AgencyPaySet.jsx
 */
import React, { useState, useEffect } from 'react'
import {
  Row, Col, Form, Input,
  Button, Table, Space,
  ConfigProvider, message
} from 'antd'

import zhCN from 'antd/es/locale/zh_CN'
import {
  SearchOutlined, PlusOutlined,
  EditOutlined, DeleteOutlined,

} from '@ant-design/icons';



import MyModal from '../../components/Modal';
import Info from './../../components/Info/AgencyPaySet'

// 引入样式
import myStyle from './CSS/AgencyPaySet.module.css'
import './../../components/HOC/HocButton/index.css'
// 引入初始数据
import {
  merchantData,
  merchantColumns,
  paymentTypeNameData,
  paymentTypeNameColumns,
  amountRelatedData,
  amountRelatedColumns,
  // rowSelection
} from '../../initData/AgencyPaySet';

import {
  allMerchantInformation,
  deleteMerchantPayment,
  paymentConfigurationData,
  queryMerchant
} from './../../API'


const rowBackground = myStyle.row_background

export default function AgencyPaySet() {
  // 定义hook 创建的 form 控制实例
  const [searchForm] = Form.useForm();
  // 初始状态
  // 商户信息表格数据
  const [initTableData, setInitTableData] = useState(merchantData);
  // 选中行信息
  const [selecRowData, setSelecRowData] = useState();
  const [selecedStatus, setSelecedStatus] = useState('false');
  // 点击左侧数据表格行数据
  const [selecLeftRowData, setSelecLeftRowData] = useState([]);
  // 点击行的key
  const [rowKey, setRowKey] = useState();
  // 点击行的key
  // 最右侧数据表格所需数据
  const [relatedData, setRelatedData] = useState(amountRelatedData);

  let [showmodal, setShowModal] = useState('true')

  // 数据总条数
  let [total, setTotal] = useState(0);
  // 每页条数
  let [pageSize, setPageSize] = useState(2);
  // 当前页
  let [current, setCurrent] = useState(1);

  // 表格行是否可选择
  let rowSelection = {
    type: 'radio',//单选
    fixed: true,//把选择框列固定在左边,
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(selectedRows);
      setSelecRowData(selectedRows[0])
      setSelecedStatus('true')
    }
  }

  const [refresh, setRefresh] = useState(false);
  const doRefresh = () => setRefresh(true)


  // 当前页和一页显示条数发生改变时调用的函数 page(current), pageSize
  const onChangePageSizeCurrent = (page, pageSize) => {
    // console.log(page, pageSize);
    setCurrent(page)
    setPageSize(pageSize)
  }

  // 搜索按钮 searchBtn 点击调用的函数
  const searchBtn = () => {
    // 获取搜索区域 input value值
    let { merchant } = searchForm.getFieldsValue()
    queryMerchant({
      condition: merchant,
      limit: pageSize,
      page: current
    }).then(res => {
      console.log(res);
      if (res.code === 0) {
        // 表格数据
        setInitTableData(handleTableData(res.data))
        // 数据总条数
        setTotal(res.count)
      }
    })
  }

  // 点击左边数据表格行
  const rowCliclk = (record) => {
    // console.log('---record---', record);
    setRowKey(record.key)

    // 查询点击商户的已有支付配置数据
    paymentConfigurationData({
      userId: record.key,
      userId: record.key,
    }).then(res => {
      if (res.code === 0) {
        setRelatedData(handleRightTableData(res.data))
        setSelecLeftRowData(record)
      }
    })

  }

  /* 处理数据 */
  // 左边数据表格
  const handleTableData = (data) => {
    // console.log(data);
    let newList = []
    data.forEach(item => {
      newList.push(
        {
          key: item.id,
          MerchantNumber: item.yongHuId,//商户号 
          MerchantName: item.nickName,//商户名称
          userName: item.name// 用户名  
        },
      )
    });
    return newList
  }
  // 右边数据表格
  const handleRightTableData = (data) => {
    let newList = []
    // console.log(data);
    data.forEach(item => {
      newList.push({
        key: item.id,
        minAmountOfMoney: item.tiXianMin,//金额(最小) 
        maxAmountOfMoney: item.tiXianMax,//金额(最大)
        serviceCharge: item.tiXianShouXu,// 手续费(元)
        rate: item.tiXianFeiLv,// 费率(%) 
        userId: item.userId
      })
    })
    return newList
  }


  // 删除按钮点击事件
  const deleteData = () => {
    let id = String(selecRowData.key)
    console.log(typeof id);
    //删除商户代付配置数据
    deleteMerchantPayment({
      id: id
    }).then(res => {
      message.success(res.msg)
      doRefresh()
    })
  }


  useEffect(() => {
    // 查询所有商户信息接口
    allMerchantInformation({
      limit: pageSize,
      page: current
    }).then(res => {
      // console.log(res.data);
      if (res.code === 0) {
        // 表格数据
        setInitTableData(handleTableData(res.data))
        // 数据总条数
        setTotal(res.count)
      }
    })
    refresh && setTimeout(() => setRefresh(false))
  }, [relatedData, selecLeftRowData, current, pageSize, refresh])



  return (

    <>
      <Row gutter={16}>
        {/* 左 */}
        <Col span={8}>
          {/* 搜索区域  商户*/}
          <Row className={myStyle.Row_margin}>
            <Form
              name="searchForm"
              form={searchForm}
              layout='inline'
              size='large'
            >
              <Col span={18} >
                <Form.Item name="merchant" >
                  <Input placeholder="商户账号/商户名称/商户号" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item >
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={searchBtn}
                  >
                    搜索
                  </Button>
                </Form.Item>
              </Col>
            </Form>
          </Row>
          {/* 数据表格 */}
          <Row>
            <Col span={24}>
              <ConfigProvider locale={zhCN}>
                <Table
                  columns={merchantColumns}
                  dataSource={initTableData}
                  tableLayout='fixed'
                  bordered
                  scroll={{ y: 600 }}
                  pagination={{
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: total => `共 ${total} 条`,
                    total: total,
                    pageSizeOptions: [2, 5, 10, 30, 50],
                    defaultPageSize: 2,
                    pageSize: pageSize,
                    current: current,
                    onChange: onChangePageSizeCurrent,
                    size: "small"
                  }}
                  onRow={record => {
                    return {
                      onClick: () => rowCliclk(record)
                    };
                  }}
                  rowClassName={
                    (record, index) => {
                      return record.key === rowKey ? rowBackground : null
                    }
                  }
                >
                </Table>
              </ConfigProvider>
            </Col>
          </Row>
        </Col>
        {/* 中 */}
        <Col span={5}>
          {/* 数据表格 */}
          <Row>
            <Col span={24}>
              <Table
                columns={paymentTypeNameColumns}
                dataSource={paymentTypeNameData}
                tableLayout='fixed'
                bordered
                pagination={false}
                scroll={{ y: 600 }}
                rowClassName={
                  (record, index) => {
                    return rowBackground
                  }
                }
              >
              </Table>
            </Col>
          </Row>
        </Col>
        {/* 右 */}
        <Col span={11}>
          {/* 按钮区域 */}
          <Row className={myStyle.Row_margin}>
            <Col span={24}>
              <ConfigProvider locale={zhCN}>
                <Space
                  align='start'
                  size='large'
                >
                  <MyModal
                    type='primary'
                    icon={<PlusOutlined />}
                    className={`${myStyle.btn_height40} green`}
                    btntext='增加'
                    title='添加代付配置'
                    showmodal={showmodal}
                  >
                    <Info
                      setshowmodal={setShowModal}
                      btntext='增加'
                      selecLeftRowData={selecLeftRowData}
                    />
                  </MyModal >
                  <MyModal
                    type='primary'
                    icon={<EditOutlined />}
                    className={`${myStyle.btn_height40} green`}
                    btntext='编辑'
                    title='修改代付配置'
                    showmodal={showmodal}
                    selecedstatus={selecedStatus}
                  >
                    <Info setshowmodal={setShowModal} btntext='编辑' selecRowData={selecRowData} />
                  </MyModal >
                  <Button type='primary'
                    icon={<DeleteOutlined />}
                    className={`${myStyle.btn_height40} red`}
                    onClick={deleteData}

                  >
                    删除
                  </Button>
                </Space>
              </ConfigProvider>
            </Col>
          </Row>
          {/* 数据表格 */}
          <Row>
            <Col span={24}>
              <Table
                columns={amountRelatedColumns}
                dataSource={relatedData}
                tableLayout='fixed'
                bordered
                pagination={false}
                rowSelection={rowSelection}
                scroll={{ y: 500 }}
              >
              </Table>
            </Col>
          </Row>
        </Col>
      </Row >
    </>
  )
}